import userApi from '@/api/userApi';
import { getUserId, getCookies } from '@/utils/cookie';

const user = {
  state: {
    id: getUserId() || 0,
    realname: getCookies('Username') || '',
    profile: '',
    username: '',
    avatar: '',
    status: 0,
    users: []
  },
  mutations: {
    setId: (state, id) => { state.id = id; },
    setProfile: (state, profile) => { state.profile = profile; },
    setUsername: (state, username) => { state.username = username; },
    setAvatar: (state, avatar) => { state.avatar = avatar; },
    setStatus: (state, status) => { state.status = status; },
    setUsers: (state, users) => { state.users = users; },
    setRealname: (state, realname) => { state.realname = realname; },
    appendUsers: (state, users) => { state.users.concat(users); }
  },
  actions: {
    GetUsers ({ commit, state }) {
      return new Promise(resolve => {
        userApi.getPage({ p: 1, pageoffset: 200 }).then(({ Users, PageNums, Page }) => {
          if (!Users) resolve(false);
          commit('setUsers', Users);
          if (PageNums < 2) resolve(true);
          const promises = new Array(PageNums - 1)
            .fill(undefined)
            .map((v, i) => {
              new Promise((resolve, reject) => {
                userApi.getPage({ p: i + 2, pageoffset: 200 }).then(appendUsers => {
                  if (!appendUsers) reject();
                  commit('appendUsers', appendUsers);
                  resolve(true);
                }).catch(() => reject());
              })
            });
          Promise.all(promises).then(() => resolve(true)).catch(() => resolve(false));
        }).catch(() => resolve(false));
      })
    }
  }
}

export default user;
